/**
 * 腾讯云上传
 */

import { server_request } from "../../utils/request";
import { session_storage } from "../../utils/storage";
import uploadConfig from "../../config/upload";


function cosUpload( file, config){
    let cos_config = uploadConfig.cos.upload_config;
    // console.log( getSts());
    // getSts()
    session_storage( "cos_sts", {
        ajax_url: uploadConfig.cos.get_sts_token_url,
        errorMsg: "获取cos临时凭证失败",
        value: config.sts,
    })
        .then( (sts) => {

            if( sts != null){
                cos_config = {
                    getAuthorization: ( options, callback) => {
                        callback( sts.credentials);
                    }
                };
            }

            toUpload( file, cos_config, config);
        })
        .catch( (msg, res) => {
            config.failure && config.failure( { code: 500, msg: msg, data: res});
        });
}

function toUpload( file, cos_config, config){

    let client = new COS( cos_config);

    try{
        let fileFinalPath = config.fileOnlinePath;
        let key = fileFinalPath;

        client.sliceUploadFile( 
            {
                Bucket: uploadConfig.cos.bucket,
                Region: uploadConfig.cos.region,
                Key: key,
                Body: file,
                onProgress: ( progress)=>{
                    config.progress && config.progress( { percent: Math.floor( progress.percent * 100)});
                }
            },
            (err, data) =>{
                if( data == null){
                    console.error( "cos upload fail", err);
                    config.failure && config.failure( { code: 500, msg: "上传失败", data: err});
                }else{

                    var loc = data.Location;
                    if( loc.indexOf( "://") == -1){
                        loc = "http" + ( uploadConfig.cos.secure ? "s" : "") + "://" + loc;
                    }

                    config.success && config.success( {
                        code: 200,
                        msg: "success",
                        data: loc
                    });
                }
            }
        );

    }catch( e){
        console.error( e);
        config.failure && config.failure( { code: 500, msg: "上传失败", data: e});
    }
}


export default function uploadFile( file, config) {
    cosUpload( file, config);
}